package com.ruoyi.dev.vo;

import com.ruoyi.common.utils.StringUtils;
import lombok.Data;

/**
 * 数据库表
 */
@Data
public class DbWhere {

    public static final String EXP_EQ = "eq";
    public static final String EXP_LT = "lt";
    public static final String EXP_LTE = "lte";
    public static final String EXP_GT = "gt";
    public static final String EXP_GTE = "gte";
    public static final String EXP_NEQ = "neq";
    public static final String EXP_LK = "lk";
    public static final String EXP_NLK = "nlk";
    public static final String EXP_IN = "in";
    public static final String EXP_BT = "bt";
    public static final String EXP_NULL = "null";
    public static final String EXP_NOT = "not";

    private String field;
    private String exp;
    private String val;

    /**
     * 预编译查询条件
     * @param field
     * @param exp
     * @return
     */
    public static String prepare(String field, String exp){
        switch (exp){
            case "lt":
                return field + " < #{" + field+"}";
            case "lte":
                return field + " <= #{" + field+"}";
            case "gt":
                return field + " > #{" + field+"}";
            case "gte":
                return field + " >= #{" + field+"}";
            case "eq":
                return field + " = #{" + field+"}";
            case "neq":
                return field + " != #{" + field+"}";
            case "lk":
                return field + " like concat('%', #{" + field+"}, '%')";
            case "in":
            default:
                return "0";
        }
    }

    public String toWhere(){
        if(StringUtils.isEmpty(field) || StringUtils.isEmpty(exp)){
            return "1";
        }
        if(StringUtils.isEmpty(val)){
            if(exp.equalsIgnoreCase("NOT")){
                return field + " is not null";
            }else if(exp.equalsIgnoreCase("NULL")){
                return field + " is null";
            }
        }else if(exp.equals(DbWhere.EXP_EQ)){
            return field + " = '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_NEQ)){
            return field + " != '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_GT)){
            return field + " > '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_GTE)){
            return field + " >= '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_LT)){
            return field + " < '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_LTE)){
            return field + " <= '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_LK)){
            return field + " like '"+val+"'";
        }else if(exp.equals(DbWhere.EXP_IN)){
            return field + " in ('"+val.replaceAll(",", "','")+"')";
        }else if(exp.equals(DbWhere.EXP_BT)){
            String[] vs = val.split(",");
            return field + " between '" + vs[0] +"' AND '"+vs[1]+"'";
        }
        return "1";
    }
}
